package ynu.edu.ky_elm_springboot3.service.impl;

import ynu.edu.ky_elm_springboot3.mapper.CartMapper;
import ynu.edu.ky_elm_springboot3.mapper.OrderDetailetMapper;
import ynu.edu.ky_elm_springboot3.mapper.OrdersMapper;
import ynu.edu.ky_elm_springboot3.po.Cart;
import ynu.edu.ky_elm_springboot3.po.OrderDetailet;
import ynu.edu.ky_elm_springboot3.po.Orders;
import ynu.edu.ky_elm_springboot3.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class OrdersServiceImpl implements OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderDetailetMapper orderDetailetMapper;
    @Autowired
    private CartMapper cartMapper;
    
    @Transactional
    @Override
    public int createOrders(Orders orders) {
        // 1.保存订单
        ordersMapper.saveOrders(orders);
        
        // 2.获取订单编号
        Integer orderId = orders.getOrderId();
        
        // 3.根据用户编号和商家编号查询购物车表中的数据
        List<Cart> cartList = cartMapper.listCart(orders.getUserId(), orders.getBusinessId());
        
        // 4.批量添加订单明细
        for(Cart cart : cartList) {
            OrderDetailet od = new OrderDetailet();
            od.setOrderId(orderId);
            od.setFoodId(cart.getFoodId());
            od.setQuantity(cart.getQuantity());
            orderDetailetMapper.saveOrderDetailet(od);
        }
        
        // 5.清空购物车
        cartMapper.removeCart(orders.getUserId(), orders.getBusinessId(), null);
        
        return orderId;
    }
    
    @Override
    public Orders getOrdersById(Integer orderId) {
        return ordersMapper.getOrdersById(orderId);
    }
    
    @Override
    public List<Orders> listOrdersByUserId(String userId) {
        return ordersMapper.listOrdersByUserId(userId);
    }
} 